/* abstract view
 * \param keyMsgBox - not unique key for gouping views (with equals data)
 * \param name - view name. Your templates must be in <name> dir: 
 <name>/view.html - common view template. Must include <name>-view class for canvas element.
 <name>/delegate.html - element template
 Controller & model on server must called
 <name>Controller.js
 <name>Model.js
 */
$.view = function (keyMsgBox, name) {
  var elements = $([])
  keyMsgBox = keyMsgBox + '_' + name
  // Example of using the Hogan Template in client/templates/chat/message.jade to generate HTML for each message
  var html = ss.tmpl[name + '-view'].render({
    key: keyMsgBox
  });

  // Append it to the div and show effect
  var msgbox = $(html)

  msgbox.getKeyBox = function() {
    return keyMsgBox
  }
  msgbox.beforeAddElement = function (element) {
    console.log('beforeAddElement default') 
    return true   
  }
  msgbox.afterAddElement = function (element) {
    console.log('afterAddElement default')    
  }
  msgbox.afterCreateView = function (view) {
    console.log('afterCreateView default')    
  }

  msgbox.afterCreateView(msgbox)

  function addMsg(key, msg) {
    // Append it to the #chatlog div and show effect //console.log(keyMsgBox + ' - ' + key);
    if(keyMsgBox === key) {
      if(!msgbox.beforeAddElement(html)) {
        return false
      }

      for(var el in elements) {
        if(elements[el].id == msg.id) {
          console.log('element already present in list! id=' + elements[el].id + '=' + msg.id)
          return false
        }
      }
      elements.push(msg)

      var msglog = msgbox.find('.' + name + '-view').first()
      var html = ss.tmpl[name + '-delegate'].render(msg);
      html = $(html)
      
      html.attr('nameBox', name )
      html.attr('keyBox', keyMsgBox )
      for(var p in msg) {
        html.attr(p, msg[p])
      }

      msglog.append(html)
      msgbox.afterAddElement(html)
      console.log('element added')
    }
    return true
  }

  msgbox.checkElement = function(msg) {
    return true
  };

  // Demonstrates sharing code between modules by exporting function
  msgbox.addElement = function (msg, cb) {
    if (msgbox.checkElement(msg)) {
      return ss.rpc(name + 'Controller.addElement', keyMsgBox, msg, cb);
    } else {
      return cb(false);
    }
  }

  // Listen out for newMessage events coming from the server
  ss.event.on('elementAdded', function(key, message, time) {
    addMsg(key, message)
  });

  // Listen out for newMessage events coming from the server
  ss.event.on('elements', function(key, messages) {
    if(elements && elements.length > 0)return null;
    $(messages).each(function(index, msg) {
      addMsg(key, msg)
    })
  });

  ss.rpc(name + 'Controller.elements', keyMsgBox, function(success) {
    console.log('received elements')
  });

  return msgbox;
};
